﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;

using TopApp.Library;

using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api.Domain;
using Top.Api.Util;

namespace TopApp
{
    public partial class MainForm : Form
    {
        delegate void SetTextCallback(object text);

        delegate void ThreadEntry(Object data);

        public MainForm()
        {

            InitializeComponent();

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.setControlState();
            Properties.Settings.Default.Upgrade();
            Properties.Settings.Default.Reload();
            this.initAutoStartThreads();
        }

        private void setControlState()
        {
            this.TradeDownload_Init_starttime_dateTimePicker.Value = System.DateTime.Parse(System.DateTime.Now.AddDays(-Convert.ToInt32(Properties.Settings.Default.trade_download_init_days)).ToShortDateString() + " 00:00:00");
            this.TradeDownload_Init_endtime_dateTimePicker.Value = System.DateTime.Parse(System.DateTime.Now.AddDays(-1).ToShortDateString() + " 23:59:59");

            this.TradeDownload_Period_lasttime.Value = Properties.Settings.Default.trade_download_period_lasttime;
            this.TradeDownload_Period_lasttime.Text = Properties.Settings.Default.trade_download_period_lasttime.ToString(this.TradeDownload_Period_lasttime.CustomFormat);

            //this.TabPageControl.TabPages["TabPage_Config"].Parent = null;
            //this.TabPageControl.TabPages["TabPage_TradeDownload"].Parent = null;
            this.TabPageControl.TabPages["TabPage_Main"].Parent = null;

            label7.Visible = false;
            InventorySyn_Period_interval.Visible = false;
            label8.Visible = false;
            InventorySyn_Period_count.Visible = false;
            label11.Visible = false;
            InventorySyn_follow_tradedownload.Visible = false;

            AppDataBase appdata = new AppDataBase();
            TradeDownload_Period_FailTradeCount.Text = appdata.getFailTradeCount().ToString();
        }

        private void initAutoStartThreads()
        {
            if (TradeDownload_autostart.Checked)
            {
                TradeDownload_start_Click(TradeDownload_start,new EventArgs());
            }
        }

        // 日志目录选择按键
        private void Config_Log_file_dir_button_Click(object sender, EventArgs e)
        {
            this.Config_App_Log_file_dir_folderBrowserDialog.ShowDialog();

            this.Config_App_Log_file_dir.Text = this.Config_App_Log_file_dir_folderBrowserDialog.SelectedPath;
        }

        // 配置保存按键
        private void Config_save_button_Click(object sender, EventArgs e)
        {

            Properties.Settings.Default.Save();

        }

        // 开始下载订单按键
        private void TradeDownload_start_Click(object sender, EventArgs e)
        {
            // 更改按键状态
            Button b = (Button)sender;
            b.Enabled = false;

            // 开启订单下载线程
            TradeDownload thd = new TradeDownload(this);
            thd.ProgressChanged += thd_ProgressChanged;
            thd.RunWorkerAsync();
        }

        private void thd_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState.ToString() == "启动次数加一")
            {
                this.TradeDownload_Period_count.Text = (Convert.ToInt64(this.TradeDownload_Period_count.Text) + 1).ToString();
            }
            else if (e.UserState.ToString() == "update fail trade count")
            {
                AppDataBase appdata = new AppDataBase();
                TradeDownload_Period_FailTradeCount.Text = appdata.getFailTradeCount().ToString();
            }
            else if (e.ProgressPercentage == 22) // 保存最后周期结束时音点到用户配置
            {
                this.TradeDownload_Period_lasttime.Value = Properties.Settings.Default.trade_download_period_lasttime = (DateTime)e.UserState;
                this.TradeDownload_Period_lasttime.Text = this.TradeDownload_Period_lasttime.Value.ToString(this.TradeDownload_Period_lasttime.CustomFormat);

                Properties.Settings.Default.Save();
            }
            else
            {
                Log log = new Log();
                TradeDownload_listBox.Items.Add(log.add(e.UserState.ToString()));
                TradeDownload_listBox.SelectedIndex = TradeDownload_listBox.Items.Count - 1;
            }
        }

        // 开始检查无效商家编码按键
        private void OuterIdCheck_Button_Click(object sender, EventArgs e)
        {
            //填充表体
            OuterIdCheck_listBox.Items.Clear();
            GetInvalidOuterId thd = new GetInvalidOuterId();
            thd.ProgressChanged += GetInvalidOuterId_Reporter;
            thd.RunWorkerAsync();
        }

        private void GetInvalidOuterId_Reporter(object sender,ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 100)
            {
                OuterIdCheck_DataGridView.DataSource = (List<Item>)e.UserState;
                OuterIdCheck_DataGridView.RowHeadersVisible = false;

                foreach (DataGridViewColumn c in OuterIdCheck_DataGridView.Columns)
                {
                    if (c.HeaderText.ToLower() == "numiid" || c.HeaderText.ToLower() == "outerid" || c.HeaderText.ToLower() == "title")
                        c.Visible = true;
                    else
                    {
                        c.Visible = false;
                        //OuterIdCheck_listBox.Items.Add(c.HeaderText.ToLower() + "列被隐藏了！");
                    }
                }
            }
            else
            {

                OuterIdCheck_listBox.Items.Add(e.UserState.ToString());
                OuterIdCheck_listBox.SelectedIndex = OuterIdCheck_listBox.Items.Count-1;

            }
        }

        // 开始库存同步按键
        private void InventorySyn_start_Click(object sender, EventArgs e)
        {
            InventorySyn_listBox.Items.Clear();
            InventorySyn thd = new InventorySyn();
            thd.ProgressChanged += InventorySyn_Reporter;
            thd.exception = this.InventorySyn_exception.Text;
            thd.RunWorkerAsync();
        }

        private void InventorySyn_Reporter(object sender, ProgressChangedEventArgs e)
        {
            InventorySyn_listBox.Items.Add(e.UserState.ToString());
            InventorySyn_listBox.SelectedIndex = InventorySyn_listBox.Items.Count-1;
        }

        private void TradeDownload_Period_Button_DelFailTrades_Click(object sender, EventArgs e)
        {
            AppDataBase appdata = new AppDataBase();
            MessageBox.Show("共删除"+appdata.deleteFailTrades().ToString()+"条记录");

            TradeDownload_Period_FailTradeCount.Text = appdata.getFailTradeCount().ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            KISInterface k = new KISInterface();

            Trade trade = new Trade();
            trade.Tid = Convert.ToInt64( tid_textBox.Text);

            Boolean status = k.deleteStockBill(trade);

            if (status) MessageBox.Show("删除成功");
            else MessageBox.Show("删除失败"+k.errMsg);

        }

        private void TabPage_FailTrades_Enter(object sender, EventArgs e)
        {
            ShowFailTrades st = new ShowFailTrades();
            st.ProgressChanged += st_ProgressChanged;
            st.RunWorkerAsync();

            
        }

        void st_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 100)
            {
                this.FailTrade_DataGridView.DataSource = (DataTable)e.UserState;
                this.FailTrade_DataGridView.RowHeadersVisible = false;

                foreach (DataGridViewColumn c in this.FailTrade_DataGridView.Columns)
                {
                    if (c.HeaderText.ToLower() == "tid")
                    {
                        c.HeaderText = "订单号";
                        c.Width = 100;
                    }

                    if (c.HeaderText.ToLower() == "fail_time")
                    {
                        c.HeaderText = "失败时间";
                        c.Width = 100;
                    }

                    if (c.HeaderText.ToLower() == "text")
                    {
                        c.HeaderText = "失败原因";
                        c.Width = 680;
                    }
                }
            }
        }

    }
}
